package com.young4j.xinsuiwutuobang.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 流操作工具类
 * @author 杨飞
 *
 */
public class StreamUtls {
	private static final Logger LOGGER = LoggerFactory.getLogger(StreamUtls.class);
	/*
	 * 从输入流中获取字符串
	 */
	public static String getString(InputStream is){
		StringBuilder sb = new StringBuilder();
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(is));
			String line;
			//括号
			while((line = reader.readLine()) != null ){
				sb.append(line);
			}
		} catch (Exception e) {
			LOGGER.error("get string failure",e);
			throw new RuntimeException(e);
		}
		return sb.toString();
	}
	/**
	 * 将输入流复制到输出流
	 * @param is
	 * @param os
	 */
	public static void copyStream(InputStream is,OutputStream os){
		try {
			int length;
			byte[] buffer = new byte[4 * 1024];
			while((length = is.read(buffer, 0, buffer.length)) != -1){
				os.write(buffer, 0, length);
			}
			os.flush();
		} catch (Exception e) {
			LOGGER.error("copy stream failure",e);
			throw new RuntimeException(e);
		}finally{
			try {
				is.close();
				os.close();
			} catch (Exception e) {
				LOGGER.error("close stream failure",e);
			}
		}
	}
}
